package com.eistert.java.algorithm.tencommonalgorithms.kmp;

/**
 * @Description: violence match
 * @Author: ai
 * @create: 2023-04-21 21:43
 */
public class ViolenceMatch {

    public static void main(String[] args) {
        String str1 = "硅硅谷 尚硅谷你尚硅 尚硅谷你尚硅谷你尚硅你好";
        String str2 = "尚硅谷你尚硅你";

        int index = violenceMatch(str1, str2);
        System.out.println("index=" + index);
    }

    public static int violenceMatch(String str1, String str2) {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = str1.length();
        int s2Len = str2.length();

        int i = 0; // i 索引指向s1
        int j = 0; // j 索引指向s2

        while (i < s1Len && j < s2Len) { // 保证匹配时，不越界
            // 匹配成功
            if (s1[i] == s2[j]) {
                i++;
                j++;
                // 没有匹配成功
            } else {
                i = i - (j - 1);
                j = 0;
            }
        }

        // 判断是否匹配成功
        return j == s2Len ? i - j : -1;
    }
}
